package com.eagle.view.fragment.meeting;

import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorManager;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eagle.R;
import com.eagle.support.common.CameraDataCallback;
import com.eagle.support.helper.CallHelper;
import com.eagle.support.utils.Utility;
import com.eagle.view.activity.MeetingActivity;
import com.eagle.view.activity.adapter.MeetingAdapter;
import com.eagle.view.fragment.live.BaseFragment;
import com.eagle.view.widget.CameraTextureView;
import com.eagle.view.widget.ConferenceRemoteVideoView;
import com.eagle.view.widget.FullyGridLayoutManager;
import com.kinstalk.voip.sdk.EngineSdkVideoPixelFormat;
import com.nineoldandroids.animation.ObjectAnimator;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.SystemService;
import org.androidannotations.annotations.ViewById;

/**
 * Created by gc on 2017/1/13.
 */
@EFragment(R.layout.fragment_meeting)
public class FragmentMeeting extends BaseFragment implements MeetingAdapter.ICameraDataCallback{

    @SystemService
    protected SensorManager mSensorManager;

    @ViewById(R.id.layout_menu)
    protected RelativeLayout mLayoutMenu;

    @ViewById(R.id.tv_room)
    protected TextView mTvRoomInfo;

    @ViewById(R.id.tv_download)
    protected TextView mTvDownload;

    @ViewById(R.id.tv_upload)
    protected TextView mTvUpload;

    @ViewById(R.id.tv_duration)
    protected TextView mTvDuration;

    @ViewById(R.id.rc_window)
    protected RecyclerView mRvWindows;

    @ViewById(R.id.btn_mute)
    protected ImageView mIvMute;

    protected CameraTextureView mCameraTextureView;

    private int mPhoneOrientation = 3;

    private int mPersonCount = 1;

    private String mRoomId;

    private MeetingActivity mActivity;

    private CallHelper mCallHelper;

    private MeetingAdapter mAdapter;

    @AfterViews
    void initView() {
        mActivity = (MeetingActivity) getActivity();
        mCallHelper = mActivity.getCallHelper();
        mAdapter = new MeetingAdapter(mActivity, this);
        mRvWindows.setLayoutManager(new FullyGridLayoutManager(mActivity, 2));
        mRvWindows.setHasFixedSize(true);
        mRvWindows.setAdapter(mAdapter);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            mAdapter.initMineWindow();
        }
    }

    public void refreshRoomInfo(String mRoomId) {
        this.mRoomId = mRoomId;
        mTvRoomInfo.setText(String.format(getString(R.string.room_info), mRoomId, mPersonCount));
    }

    public void onPushAddCid(String cid) {
        if (!TextUtils.isEmpty(cid)) {
            mPersonCount++;
            refreshRoomInfo(mRoomId);
            mAdapter.addRemoteWindow(cid);
        }
    }

    public void onPushByeCid(String cid) {
        if (!TextUtils.isEmpty(cid)) {
            mPersonCount--;
            refreshRoomInfo(mRoomId);
            mAdapter.removeRemoteWindow(cid);
        }
    }

    /**
     * 流量监听
     */
    public void receiverSpeed(String rx, String tx) {
        mTvDownload.setText(rx);
        mTvUpload.setText(tx);
    }

    public void onMainVideoDataInCall(long pointer, int width, int height, char rotation, long channelId) {
        try {
            for (String key : mAdapter.getViewMaps().keySet()) {
                Log.e("cim", "onMainVideoDataInCall: " + key + channelId );
            }
            if (mAdapter.getViewMaps().containsKey(channelId)) {
                ConferenceRemoteVideoView remoteView = mAdapter.getViewMaps().get(channelId);
                remoteView.process(pointer, width, height, rotation);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        switch (event.sensor.getType()) {
            case Sensor.TYPE_ACCELEROMETER:
                int newOrientation = Utility.getDirection((int) event.values[0], (int) event.values[1], (int) event.values[2]);
                if (mPhoneOrientation != newOrientation) {
                    mPhoneOrientation = newOrientation;
                }
                break;
            case Sensor.TYPE_PROXIMITY:
                // onProximityChanged(event);
                break;
            default:
                break;
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void onCameraData(byte[] data, android.hardware.Camera camera) {
        Camera.Size size = camera.getParameters().getPreviewSize();
        if (mCallHelper.getLoader().getCurrentCallInfo() != null && !isHidden() && mAdapter.getCameraTextureView() != null) {
            // 如果是前置摄像头， 需要将图像上下翻转
            int orientation = mPhoneOrientation;
            if (mAdapter.getCameraTextureView().getCameraId() == Camera.CameraInfo.CAMERA_FACING_FRONT && orientation % 2 == 1) {
                orientation = (orientation + 2) % 4;
            }
            mCallHelper.getLoader().getCurrentCallInfo().sendDataOnMainVideoChannel(EngineSdkVideoPixelFormat.ES_PIXEL_FORMAT_NV21, size.width, size.height, (char) orientation, data);
        }
    }

    /**
     * 显示隐藏菜单
     */
    @Click(R.id.layout_meeting_menu)
    protected void showMenu() {
        mActivity.showMenu();
    }

    @Click(R.id.btn_mute)
    protected void onMute() {
        mIvMute.setImageResource(mCallHelper.isSoundOff() ? R.mipmap.ic_mute : R.mipmap.ic_mute_blue);
        mCallHelper.getLoader().getCurrentCallInfo().setTransmitingAudioMute(!mCallHelper.isSoundOff());
    }

    @Click(R.id.btn_switch)
    protected void switchCamera() {
        mCameraTextureView.changeCamera();
        mCameraTextureView.postDelayed(() -> ObjectAnimator.ofFloat(mCameraTextureView, "rotationY", 0.0F, 180.0F).setDuration(300).start(), 150);
    }

    @Click(R.id.btn_hang_up)
    protected void onHangup() {
        mActivity.popQuitLiveDialog();
    }

    public void stopCameraPreview() {
        if (mCameraTextureView != null) {
            mCameraTextureView.destroyCamera();
        }
    }
}
